package com.neusoft.yiyang.auth.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenProvider jwtTokenProvider;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        // 1. 从请求头中提取Token
        String authHeader = request.getHeader("Authorization");
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7); // 去除"Bearer "前缀
        }

        // 2. 验证Token并设置认证信息
        if (token != null && jwtTokenProvider.validateToken(token)) {
            // 这里可以从Token中提取用户名或用户ID作为认证主体
            // （实际项目中可根据需要从Token中解析用户信息）
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    "authenticatedUser", // 用户名/用户ID（根据实际情况修改）
                    null,
                    Collections.emptyList() // 权限列表（实际项目中需从Token解析）
            );
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            
            // 将认证信息存入SecurityContext，后续接口可通过SecurityContext获取
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        // 3. 继续执行过滤链
        filterChain.doFilter(request, response);
    }
}